#include "StomperLib/Controls/EditorObjectTree.h"
namespace StomperLib {
namespace Controls {

GWEN_CONTROL_CONSTRUCTOR( EditorObjectTree )
{
}

void EditorObjectTree::AddCollector( StomperLib::EditorObjectCollector* collector )
{
  this->m_Collectors.push_back( collector );
  this->m_AddGlobalSelection = false;
}

void EditorObjectTree::SetAddGlobalSelection( bool value )
{
  this->m_AddGlobalSelection = value;
}

void EditorObjectTree::CollectItems( )
{
  this->Clear( );

  for (auto collector = m_Collectors.begin( ); collector != m_Collectors.end( ); ++collector)
  {
    this->AddItems((*collector)->CollectObjects( this->m_Game->getFileSystem( )), (*collector)->GetHeader( ));
  }
}

void EditorObjectTree::AddItems( std::shared_ptr<std::vector<FileInfoObjectTuple> > items, std::string header )
{
  for (auto tuple = items->begin( ); tuple != items->end( ); ++tuple)
  {
    if (this->m_AddGlobalSelection)
      this->AddItemGlobal( *tuple, header );
    else
      this->AddItem( *tuple );
  }

  this->ExpandAll( );
}

void EditorObjectTree::AddItem( FileInfoObjectTuple tuple )
{
  auto nodeName = this->AddFile( tuple.fileInfo )->GetName( );

  this->AddFile( nodeName, tuple.object->Name );
}

void EditorObjectTree::AddItemGlobal( FileInfoObjectTuple tuple, std::string header )
{
  auto baseName = tuple.fileInfo.name.substr( 0, tuple.fileInfo.name.find_first_of( "." ));

  auto baseNode = this->AddFile( tuple.fileInfo.path, baseName );
  auto baseNodeName = baseNode->GetName( );

  auto subHeader = this->AddFile( baseNodeName, header );
  auto subHeaderName = subHeader->GetName( );

  this->AddFile( subHeaderName, tuple.object->Name );

  auto globNodeName = baseNodeName;
  globNodeName.append( "/" );
  globNodeName.append( tuple.object->Name );

  auto globNode = this->FindChild<Gwen::Controls::TreeNode>( globNodeName, true );

  if (globNode == NULL)
    globNode = this->AddFile( baseNodeName, tuple.object->Name );
}

}

}